local typedefs = require "kong.db.schema.typedefs"

local function is_empty(s)
  return s == nil or s == ''
end

local function validate_flows(config)
  if is_empty(config.provision_key)
    or is_empty(config.kong_admin)
  then
    return nil, "must not empty"
  end

  return true
end

return {
  name = "oauth2-client",
  fields = {
    { consumer = typedefs.no_consumer },
    { protocols = typedefs.protocols_http },
    { config = {
        type = "record",
        fields = {
          { provision_key = { type = "string", unique = true, auto = true, required = true }, },
          { kong_admin = { type = "string", unique = true, auto = true, required = true }, },
          { kong_api = { type = "string", unique = true, auto = true, required = true }, },
          { api_path = { type = "string", unique = true, auto = true, required = true }, },
          { service_host = { type = "string", unique = true, auto = true, required = true }, },
          { scopes = { type = "array", elements = { type = "string" }, }, },
          { client_id = { type = "string", unique = true, auto = true, required = true }, },
          { client_secret = { type = "string", unique = true, auto = true, required = true }, },
          { service_host = { type = "string", unique = true, auto = true, required = true }, },
          { redirect_uri = { type = "string", unique = true, auto = true, required = true }, },
        },
        custom_validator = validate_flows,
        entity_checks = {
          { conditional = {
              if_field = "provision_key",
              if_match = { required = true },
              then_field = "scopes",
              then_match = { required = true },
          }, },
        },
      },
    },
  },
}


